import { FC, memo, useState } from 'react';
import { useContextSelector } from './createContext';

import Provider, {Context} from './Provider'

function useStoreApi() {
  const context = useContextSelector(Context, (v) => ({
    setCount1: v?.setCount1,
    setCount2: v?.setCount2,
  }));

  if (!context) {
    throw new Error('xxx');
  }

  return context;
}

function useCount1() {
  const context = useContextSelector(Context, (v) => ({
    count1: v?.count1,
    setCount1: v?.setCount1,
  }));

  if (!context) {
    throw new Error('xxx');
  }

  return context;
}

function useCount2() {
  const context = useContextSelector(Context, (v) => ({
    count2: v?.count2,
    setCount2: v?.setCount2,
  }));

  if (!context) {
    throw new Error('xxx');
  }

  return context;
}

const Count1 = memo(() => {
  const { count1, setCount1 } = useCount1();

  console.log('render count1');

  return (
    <div>
      <button onClick={() => setCount1!(count1! + 1)}>count1: {count1}</button>
    </div>
  );
});

const Count2 = memo(() => {
  const { count2, setCount2 } = useCount2();

  console.log('render count2');

  return (
    <div>
      <button onClick={() => setCount2!(count2! + 1)}>count2: {count2}</button>
    </div>
  );
});

const Reset = memo(() => {
  const { setCount1, setCount2 } = useStoreApi();

  console.log('reset render');

  return (
    <div style={{ margin: '10px 0' }}>
      <button onClick={() => setCount1!(0)}>reset count1</button>
      <button onClick={() => setCount2!(0)}>reset count2</button>
    </div>
  );
});

const App: FC<{ name: string }> = ({ name }) => {
  const [count, setCount] = useState(0);

  console.log('app render');

  return (
    <div>
      <Provider>
        <div>
          <h1>Hello {name}!</h1>
          <p>Start editing to see some magic happen :)</p>
          <Count1 />
          <Count2 />
        </div>
        <Reset />
      </Provider>
      <button onClick={() => setCount(count + 1)}>count3: {count}</button>
    </div>
  );
};

export default App;